//
//  QLMRegisterUserNameVC.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/10/17.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMRegisterUserNameVC.h"

@interface QLMRegisterUserNameVC ()<UITextFieldDelegate>{
    
    BOOL _isBtn1Selcted;
    BOOL _isBtn2Selcted;
    
    NSString *custLinkmanId;
    NSString *custLinkmanName;
    
    NSArray *_list;
}

@end

@implementation QLMRegisterUserNameVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title=@"个人信息";
    _list=[NSArray array];
    
    self.name1Btn.titleLabel.font=[UIFont systemFontOfSize:14];
    self.name2Btn.titleLabel.font=[UIFont systemFontOfSize:14];
    self.telLabel.font=[UIFont systemFontOfSize:14];
    self.usernameTF.font=[UIFont systemFontOfSize:14];
    self.registerBtn.titleLabel.font=[UIFont systemFontOfSize:14];
    
    self.name1Btn.hidden=YES;
    self.name2Btn.hidden=YES;
    self.telLabel.hidden=YES;
    
    if (self._isLoginTo) {
        [self.registerBtn setTitle:@"设置关联" forState:UIControlStateNormal];
    }else{
        [self.registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    }
    
    UIView *lineView=[[UIView alloc] initWithFrame:CGRectMake(_telLabel.frame.origin.x, _usernameTF.frame.size.height+_usernameTF.frame.origin.y, kScreen_width-(_telLabel.frame.origin.x)*2, 0.5)];
    lineView.backgroundColor=[UIColor lightGrayColor];
    [self.view addSubview:lineView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self _requestNameInfoAction];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UIButton Action
- (void)_changeBtnStateWithBtn:(UIButton *)btn andImageName:(NSString *)imageName WithTitleColor:(UIColor *)color{
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
}

- (IBAction)_selectBtnAction:(UIButton *)sender{
    
    _usernameTF.text=@"";
    _usernameTF.placeholder=@"请输入真实姓名";
    [self.usernameTF resignFirstResponder];
    
    if (sender.tag==640) {
        
        if (_isBtn1Selcted) {
            [self _changeBtnStateWithBtn:self.name1Btn andImageName:@"name_uns" WithTitleColor:[UIColor darkGrayColor]];
            _isBtn1Selcted=NO;
            custLinkmanId=@"";
            custLinkmanName=@"";
        }else{
            [self _changeBtnStateWithBtn:self.name1Btn andImageName:@"name_sel" WithTitleColor:kButtonColor];
            _isBtn1Selcted=YES;
            custLinkmanId=  [NSString stringWithFormat:@"%@",_list[0][@"saleCustId"]];
            custLinkmanName=[NSString stringWithFormat:@"%@",_list[0][@"saleCustName"]];
        }
        [self _changeBtnStateWithBtn:self.name2Btn andImageName:@"name_uns" WithTitleColor:[UIColor darkGrayColor]];
        
    }else{
        
        if (_isBtn2Selcted) {
            [self _changeBtnStateWithBtn:self.name2Btn andImageName:@"name_uns" WithTitleColor:[UIColor darkGrayColor]];
            _isBtn2Selcted=NO;
            custLinkmanId=@"";
            custLinkmanName=@"";
        }else{
            [self _changeBtnStateWithBtn:self.name2Btn andImageName:@"name_sel" WithTitleColor:kButtonColor];
            _isBtn2Selcted=YES;
            custLinkmanId=  [NSString stringWithFormat:@"%@",_list[1][@"saleCustId"]];
            custLinkmanName=[NSString stringWithFormat:@"%@",_list[1][@"saleCustName"]];
        }
        [self _changeBtnStateWithBtn:self.name1Btn andImageName:@"name_uns" WithTitleColor:[UIColor darkGrayColor]];
        
    }
}

- (IBAction)registerBtnAction:(UIButton *)sender {
    if (self._isLoginTo) {
        [self _comfireUserInfoData];
    }else{
        [self _requestregisterData];
    }
}

#pragma mark - UITextField delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSString *newStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSInteger res = 300-[newStr length];

    if (newStr.length!=0) {
        custLinkmanId=@"";
        custLinkmanName=@"";
        _isBtn1Selcted=NO;
        _isBtn2Selcted=NO;
        [self.name1Btn setImage:[UIImage imageNamed:@"name_uns"] forState:UIControlStateNormal];
        [self.name1Btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];

        [self.name2Btn setImage:[UIImage imageNamed:@"name_uns"] forState:UIControlStateNormal];
        [self.name2Btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    }

    if(res >= 0){
        return YES;
    }else{
        if (abs(res)>[string length]) {//abs() 取绝对值
            return NO;
        }
        NSRange rg = {0,[string length]+res};
        if (rg.length>0) {
#warning 提交新版本之前先测试下注册流程是否有问题
            NSString *s = [string substringWithRange:[string rangeOfComposedCharacterSequencesForRange:rg]];//rg];
            [textField setText:[textField.text stringByReplacingCharactersInRange:range withString:s]];
        }
        return NO;
    }
}

#pragma mark - request data
- (void)_requestNameInfoAction{
    
    NSString *urlpathStr=@"/auth/getConnect";
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    [dic setObject:self.phoneNumber forKey:@"phoneNumber"];
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:urlpathStr withParamers:dic andBody:nil
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            _list=responseObject[@"list"];
                            
                            self.telLabel.hidden=NO;
                            NSString *telStr=[NSString stringWithFormat:@"系统中发现已有人和%@关联，以下是否是您的真实姓名？",_phoneNumber];
                            NSMutableAttributedString *aString=[[NSMutableAttributedString alloc] initWithString:telStr];
                            [aString addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xf5c407) range:NSMakeRange(9, 11)];
                            
                            self.telLabel.attributedText= aString;
                            
                            if (_list.count==0) {
                                self.name1Btn.hidden=YES;
                                self.name2Btn.hidden=YES;
                                self.telLabel.hidden=YES;
                            }else if (_list.count==1){
                                self.name1Btn.hidden=NO;
                                self.name2Btn.hidden=YES;
                                [self.name1Btn setTitle:_list[0][@"linkmanName"] forState:UIControlStateNormal];
                            }else{
                                self.name1Btn.hidden=NO;
                                self.name2Btn.hidden=NO;
                                [self.name1Btn setTitle:_list[0][@"linkmanName"] forState:UIControlStateNormal];
                                [self.name2Btn setTitle:_list[1][@"linkmanName"] forState:UIControlStateNormal];
                            }
                            
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)_requestregisterData{
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    [dic setObject:self.phoneNumber forKey:@"phoneNumber"];
    [dic setObject:self.code forKey:@"code"];
    [dic setObject:self.password forKey:@"password"];
    [dic setObject:self.registerEquipmentCode forKey:@"invitationCode"];
    
    NSString *userNameStr=nil;
    if (custLinkmanId.length!=0) {
        [dic setObject:custLinkmanId forKey:@"jrUserId"];
        userNameStr=custLinkmanName;
    }else{
        userNameStr=self.usernameTF.text;
    }
    
    if (userNameStr.length==0) {
        return;
    }
    
    [dic setObject:userNameStr forKey:@"userName"];
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPathAndFormData:@"/auth/register" withParamers:dic andBody:nil
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            ETToastWithDelay(@"恭喜您，注册成功！", 1);
                            [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(delayShowProHud) userInfo:nil repeats:NO];
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)delayShowProHud{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)_comfireUserInfoData{
    
    if ([custLinkmanId length]==0&&_usernameTF.text.length==0) {
        ETToast(@"请输入或选择名字");
        return;
    }
    
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    
    if ([custLinkmanId length]!=0) {
        [dic setObject:custLinkmanId forKey:@"jrUserId"];
    }

    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/auth/setConnect" withParamers:dic andBody:tokenDic
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            [self.navigationController popToRootViewControllerAnimated:YES];
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
